# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: client_modle.py
Author: kij
Create Date: 2021/3/20
-------------------------------------------------
"""
import os
import json
import shelve
from conf import setting, http_utils


class Clent(object):
	"""
	具体数据请求逻辑处理
	"""

	def __init__(self, request=None, name=None, password=None):
		self.request = request
		self.name = name
		self.password = password
		self.context_path = '/'
		self.shelve_obj = shelve.open("luffy_db")

	def upload(self, file):
		"""
		上传文件，上传完成文件返回上传状态信息，是否上传完成
		:return:
		"""
		print(file.get('message')[0])

		http_utils.send_file(self.request, file.get('message')[0])

	def download(self, msg):
		"""
		下载方法，下载文件，返回下载完成信息
		:return:
		"""
		file_abs_path = msg.get('file_path')
		self.shelve_obj[file_abs_path] = [msg.get('file_size'), "%s.download" % msg.get('file_name')]
		# 不close不会保存
		self.shelve_obj.close()
		local_path = os.path.join(setting.BASE_DIR, "%s.download" % msg.get('message')[0])
		http_utils.save_file(self.request, local_path)
		self.shelve_obj = shelve.open("luffy_db")
		del self.shelve_obj[file_abs_path]
		os.rename(local_path, os.path.join(setting.BASE_DIR, msg.get('file_name')))

	def re_get_file(self, msg):
		"""
		下载方法，下载文件，返回下载完成信息
		:return:
		"""

		file_abs_path = msg.get('file_path')
		self.shelve_obj[file_abs_path] = [msg.get('file_size'), "%s.download" % msg.get('file_name')]
		# 不close不会保存
		self.shelve_obj.close()
		local_path = os.path.join(setting.BASE_DIR, "%s.download" % msg.get('message')[0])
		http_utils.re_save_file(self.request, local_path, msg.get('file_size'), msg.get('already_read_size'))
		self.shelve_obj = shelve.open("luffy_db")
		del self.shelve_obj[file_abs_path]
		os.rename(local_path, os.path.join(setting.BASE_DIR, msg.get('file_name')))

	def logon(self):
		"""
		登录方法，登录成功后拿到根目录路径并显示，还有用户信息
		:return:
		"""
		http_utils.send_data(self.request, self.make_data(type='logon', name=self.name, password=self.password))
		setting.data_dict.clear()
		self.context_path = '/'
		return http_utils.recv_data(self.request)

	@classmethod
	def register(cls, request, name, password):
		"""
		登录方法，登录成功后拿到根目录路径并显示，还有用户信息
		:return:
		"""
		http_utils.send_data(request, cls.make_data(type='register', name=name, password=password))
		res = http_utils.recv_data(request)
		return res

	@classmethod
	def make_data(cls, **kwargs):
		"""
		封装数据发送
		:param kwargs:
		:return:
		"""
		setting.data_dict.update(kwargs)
		return json.dumps(setting.data_dict)

	def send_func2server(self, msg):
		"""
		上传文件，上传完成文件返回上传状态信息，是否上传完成
		:return:
		"""
		# 发送服务器数据等等待返回结果
		http_utils.send_data(self.request, self.make_data(
			type=msg[0],
			name=self.name,
			message=msg[1:],
			context_path=self.context_path
		))
		res = http_utils.recv_data(self.request)
		return res
